import React, {Component} from 'react'

const Initial = <span>删除</span>
const Pending = <span><i className="am-icon-spinner am-icon-spin"></i></span>
const Resolve = <span>成功</span>
const Reject = <span>失败</span>

class AsyncButton extends Component {
    constructor(props) {
        super(props)
        this.state = {
            status: 'initial'
        }
    }

    to() {
        this.setState({status: 'pending'})
        return $.ajax(this.props.to, {
            dataType: 'json'
        }).done(res => {
            this.setState({status: 'resolve', response: res})
            this.props.onResolve(res)
        }).error(
            e => {
                this.setState({status: 'reject', error: e})
                this.props.onReject(e)
            }
        )
    }

    render () {
        let {status} = this.state
        return (
            <button className="async-button" onClick={this.to.bind(this)}>
                {status === 'pending'
                    ? this.props.pending
                    : status === 'resolve'
                    ? this.props.resolve
                    : status === 'initial'
                    ? this.props.initial
                    : this.props.reject
                }
            </button>
        )
    }
}

AsyncButton.defaultProps = {
    initial: Initial,
    pending: Pending,
    resolve: Resolve,
    reject: Reject,
    onResolve: () => null,
    onReject: () => null
}


export default AsyncButton